#pragma once

namespace Network
{
class ThreadMutex
{
	public:
		ThreadMutex(void)
		{
			mutex = CreateMutex(NULL,false,NULL);
			//InitializeCriticalSectionAndSpinCount(&mutex, 0x00000400);
			//InitializeCriticalSection(&mutex);
		}

		~ThreadMutex(void)
		{
			CloseHandle(mutex);
			//LeaveCriticalSection(&mutex);
			//DeleteCriticalSection(&mutex);
		}

		void Acquire(int ms = INFINITE)
		{
			WaitForSingleObject(mutex, ms);
			
			//This is handling for VS debugger; Press continue few times for this exception to be skipped;
			//It is not a real error outside of the debugger
			//__try{
			//	EnterCriticalSection(&mutex);
			//}__except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION)
			//{
			//}
		}

		void Wait(int ms = INFINITE)
		{
			WaitForSingleObject(mutex, ms);
		}

		void Release()
		{
			ReleaseMutex(mutex);
			//LeaveCriticalSection(&mutex);
		}

	private:
		//HANDLE mutex;
		mutable HANDLE mutex;
		ThreadMutex(const ThreadMutex&);
		void operator=(const ThreadMutex&);
	};
}